package info.qingshui.browser.hk.proxy;


import java.util.*;

import android.content.Context;
import android.util.Log;

public class ProxyManager {
	private static ProxyManager proxyManager = null;
	
	private Map<String,SortedSet<Proxy> > hostProxys = new HashMap<String,SortedSet<Proxy>>();
	private  Context ctx;
	private boolean setProxy =false;
	
	private ProxyManager( Context ctx) {
		this.ctx = ctx;
	}
	
	public static ProxyManager getProxyManager( Context ctx) {
		if ( proxyManager == null ) {
			proxyManager = new ProxyManager( ctx );
		}
		return proxyManager;
	}

	public void setProxy( String host) {
		Log.d(ProxyManager.class.getSimpleName(), "setProxy ..." + host);
		SortedSet<Proxy> proxys = hostProxys.get( host);
		if ( proxys == null ) {
			//proxys = Setting.getSetting(ctx).getProxys();
			if ( hostProxys.size() > 100 ) {
				//清空
				hostProxys.clear();
			}
			hostProxys.put(host, proxys);
		}
		
		Proxy cProxy = proxys.first();
		ProxySettings.setProxy(ctx, cProxy.getHost(), cProxy.getPort() );
		cProxy.addInvokeCount();

		setProxy = true;
		Log.d(ProxyManager.class.getSimpleName(), "setProxy :" + host);
	}
	
	
	public void proxyFail( String host) {
		if ( setProxy ) {
			Log.d(ProxyManager.class.getSimpleName(), "proxyFail ..." + host);
			SortedSet<Proxy> proxys = hostProxys.get( host);
			if ( proxys != null ) {
				Proxy cProxy = proxys.first();
				if ( cProxy != null ) {
					cProxy.addFailCount();
				}
				
				//重新排序 TODO 这么排序耗费资源，将就着用
				TreeSet<Proxy> proxys2 = new TreeSet<Proxy>();
				for( Proxy p: proxys) {
					proxys2.add(p);
				}
				hostProxys.put(host, proxys2);
			}
			
			setProxy = true;
			Log.d(ProxyManager.class.getSimpleName(), "proxyFail " + host + "|" + hostProxys.get( host));
		}
	}
}
